/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package org.apache.druid.server.coordinator.balancer;

import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import org.apache.druid.java.util.common.concurrent.Execs;
import org.apache.druid.java.util.common.logger.Logger;

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "strategy", defaultImpl = CostBalancerStrategyFactory.class)
@JsonSubTypes(value = {
    @JsonSubTypes.Type(name = "cost", value = CostBalancerStrategyFactory.class),
    @JsonSubTypes.Type(name = "cachingCost", value = DisabledCachingCostBalancerStrategyFactory.class),
    @JsonSubTypes.Type(name = "diskNormalized", value = DiskNormalizedCostBalancerStrategyFactory.class),
    @JsonSubTypes.Type(name = "random", value = RandomBalancerStrategyFactory.class)
})
public abstract class BalancerStrategyFactory
{
  private static final Logger log = new Logger(BalancerStrategyFactory.class);

  public abstract BalancerStrategy createBalancerStrategy(int numBalancerThreads);

  private int cachedBalancerThreadNumber;
  private ListeningExecutorService balancerExec;

  public void stopExecutor()
  {
    if (balancerExec != null) {
      balancerExec.shutdownNow();
      balancerExec = null;
    }
  }

  protected ListeningExecutorService getOrCreateBalancerExecutor(int balancerComputeThreads)
  {
    if (balancerExec == null) {
      balancerExec = createNewBalancerExecutor(balancerComputeThreads);
    } else if (cachedBalancerThreadNumber != balancerComputeThreads) {
      log.info(
          "'balancerComputeThreads' has changed from [%d] to [%d].",
          cachedBalancerThreadNumber, balancerComputeThreads
      );
      balancerExec.shutdownNow();
      balancerExec = createNewBalancerExecutor(balancerComputeThreads);
    }

    return balancerExec;
  }

  private ListeningExecutorService createNewBalancerExecutor(int numThreads)
  {
    cachedBalancerThreadNumber = numThreads;
    return MoreExecutors.listeningDecorator(
        Execs.multiThreaded(numThreads, "coordinator-cost-balancer-%s")
    );
  }
}
